<?php


namespace App\Controller\Frontend;


use App\Entity\Menu;
use App\Entity\PageTag;
use App\Enum\MenuEnum;
use App\Utils\Traits\JsonTrait;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class NavigationController extends AbstractController {
    use JsonTrait;

    private $limit = 9;

    /**
     * 导航菜单页
     * @param Request $request
     * @param EntityManagerInterface $em
     * @param PaginatorInterface $paginator
     * @Route("/nav/{menu}", name="navigation_page")
     * @return array|\Symfony\Component\HttpFoundation\Response
     */
    public function index (Request $request, EntityManagerInterface $em, PaginatorInterface $paginator) {
        $alias = $request->get('menu', null);
        if (is_null($alias)) {
            $this->redirect('home_page');
        }

        $menu = $this->getDoctrine()->getRepository(Menu::class)->findOneBy(['alias' => $alias, 'url' => null]);
        if (!is_object($menu)) {
            return $this->redirectToRoute('not_found_page');
        }

        if ($menu->getPageCategoryId()) {
            $dql = "SELECT p.id,p.title,p.thumbnail,p.publish_time,p.page_like,p.page_tags,p.summary,c.value as category,a.avatar,a.username,a.nickname
                    from App\Entity\Page as p 
                    left join App\Entity\PageCategory as c with p.page_category_id = c.id 
                    left join App\Entity\AdminUser as a with p.admin_user_id = a.id 
                    where p.status = 1 and p.page_category_id = ".$menu->getPageCategoryId()." order by p.id DESC ";
        } else {
            $dql = "SELECT p.id,p.title,p.thumbnail,p.publish_time,p.page_like,p.page_tags,p.summary,c.value as category,a.avatar,a.avatar,a.username,a.nickname
                    from App\Entity\Page as p 
                    left join App\Entity\PageCategory as c with p.page_category_id = c.id 
                    left join App\Entity\AdminUser as a with p.admin_user_id = a.id 
                    where p.status = 1 order by p.id DESC ";
        }
        $query = $em->createQuery($dql);
        $pagination = $paginator->paginate($query, $request->query->getInt('page', 1), $this->limit);

        // 获取对应标签
        $page_tags = $this->getDoctrine()->getRepository(PageTag::class)->findAllToArray();
        $pages = $pagination->getItems();
        foreach ($pages as &$page) {
            $items = [];
            foreach ($page['page_tags'] as $tag_id) {
                if (isset($page_tags[$tag_id])) {
                    array_push($items, $page_tags[$tag_id]);
                }
            }
            $page['page_tags'] = $items;
        }
        $pagination->setItems($pages);

        $template = $this->getTemplateByStyle($menu->getStyle());
        return $this->render($template, [
            'menu'       => $menu,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 根据menu.style获取对应的模板
     * @param $style
     * @return string
     */
    private function getTemplateByStyle ($style) {
        $result = 'frontend/navigation/list.html.twig';

        switch ($style) {
            case MenuEnum::STYLE_LIST:
                $result = 'frontend/navigation/list.html.twig';
                break;
            case MenuEnum::STYLE_IMAGE:
                $result = 'frontend/navigation/image.html.twig';
                break;
        }

        return $result;
    }


    /**
     * 图片模式下获取更多文章
     * @param Request $request
     * @param EntityManagerInterface $em
     * @param PaginatorInterface $paginator
     * @Route("/navigation/image_load_more", name="navigation_image_load_more", methods={"POST"})
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function imageLoadMore (Request $request, EntityManagerInterface $em, PaginatorInterface $paginator) {
        if (!$request->isXmlHttpRequest()) {
            return $this->jsonFailure('请求错误');
        }

        $offset = $request->request->getInt('offset', 1) + 1;
        $page_category_id = $request->request->getInt('page_category_id', 0);

        $dql = "SELECT p.id,p.title,p.thumbnail,p.publish_time,p.page_like,p.summary,c.value as category,a.avatar,a.username,a.nickname
                    from App\Entity\Page as p 
                    left join App\Entity\PageCategory as c with p.page_category_id = c.id 
                    left join App\Entity\AdminUser as a with p.admin_user_id = a.id 
                    where p.status = 1 and p.page_category_id = ".$page_category_id." order by p.id DESC";

        $query = $em->createQuery($dql);
        $pagination = $paginator->paginate($query, $offset, $this->limit);

        return $this->render('frontend/navigation/image_load_more.html.twig', [
            'pagination' => $pagination,
            'total'      => count($pagination->getItems()),
            'offset'     => $offset,
        ]);
    }

}